package com.zhongkai.service;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.zhongkai.dao.BaseDao;
import com.zhongkai.json.JSONObject;
import com.zhongkai.model.book.TCsCclxdz;

public class BaseService {

	private BaseDao baseDao;

	public BaseDao getBaseDao() {
		return baseDao;
	}
	@Resource
	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}
	public void delete(Object object) throws Exception {
		baseDao.delete(object);
	}
	public void insert(Object object) throws Exception {
		baseDao.insert(object);
	}
	public void update(Object object) throws Exception {
		baseDao.update(object);
	}

	public void insertOrUpdate(Object object) throws Exception {
		baseDao.insertOrUpdate(object);
	}

	public Object selectById(String entityName, Serializable id)
			throws Exception {
		return baseDao.selectById(entityName, id);
	}

	public Object selectById(Class entityClass, Serializable id)
			throws Exception {
		return baseDao.selectById(entityClass, id);
	}
	public List select(String hql) throws Exception {
		return baseDao.select(hql);
	}
	public List select(String hql, Object value) throws Exception {
		return baseDao.select(hql, value);
	}
	public List select(String hql, Object[] values) throws Exception {
		return baseDao.select(hql, values);
	}
	public List select(String hql,Integer pageIndex,Integer pageMax) {
		return baseDao.select(hql, pageIndex, pageMax);
	}
	
	public Integer count(String hql) throws Exception {
		return baseDao.count(hql);
	}
	public Integer count(String tablename,String where) throws Exception {		
		return baseDao.count(tablename,where);		
	}
	public void exec(String hql, Object[] values) throws Exception {
		baseDao.exec(hql, values);
	}
	public void del(String hql) throws Exception {
		baseDao.del(hql);
	}
	public Object findBySql(final String sql) throws Exception {
		return baseDao.findBySql(sql);
	}
	public void executeHQL(final String hql, final Object[] values) throws Exception{
		baseDao.executeHQL(hql, values);
	}
	/**
	 * 可以返回一个List集合中第一条记录，适用于一个表中，某字段值为唯一，但该字段是非主键的时候使用
	 * 	getSingle(类.class,“字段名”, “字段值”)
	 * 例如：
	 * 	TCsCclxdz cclxdz=(TCsCclxdz)getSingle(TCsCclxdz.class,“jjcclxDm”, “1001”)
	 * @author 梁文敏
	 * **/
	public Object getSingle(Class model,String propertyName, Object value) throws Exception{
		StringBuffer hql=new StringBuffer("from ").append(model.getName()).append(" where ").append(propertyName).append(" = ?");
		List list = baseDao.select(hql.toString(), value);
		if(list!=null && list.size()>0)
			return list.get(0);
		return null;
	}

	
	/**
	 * 
	 * 通过交警车船类别获取税局车船类别
	 * @author 吴嘉俊
	 * @param JjcclxDM
	 * @return
	 * @throws Exception
	 */
	public TCsCclxdz JjcclxDM2SwcclxDm(String JjcclxDM) throws Exception{
		List list=baseDao.select("from TCsCclxdz where jjcclxDm=?", new Object[]{JjcclxDM});
		if(list!=null && list.size()>0)
			return (TCsCclxdz)list.get(0);
		return null;
	}
	
	/**
	  * @将POJO对象转成JSON
	  */

	 public static Map pojotomap(Object obj) {
	  Map pojomap = new HashMap();
	  String newfieldName,tmp,fieldName;
	  try {
	   Class c = obj.getClass();
	   //Field m[]=c.getDeclaredFields();
	   Method m[] = c.getDeclaredMethods();
	   for (int i = 0; i < m.length; i++) {
	    if (m[i].getName().indexOf("get")==0) {
	      //System.out.println("方法名："+m[i].getName());
	     // System.out.println("值："+ m[i].invoke(obj, new Object[0]));
	    	fieldName=m[i].getName();
	    	tmp=fieldName.substring(3,4);
	    	newfieldName=tmp.toLowerCase();
	    	tmp=fieldName.substring(4);
	    	newfieldName+=tmp;
	    	//newfieldName=newfieldName.substring(3,1).toLowerCase() +newfieldName.substring(4);
	    	pojomap.put(newfieldName, m[i].invoke(obj, new Object[0]));
	    }
	   }
	  } catch (Throwable e) {
	   System.err.println(e);
	  }
	  return pojomap;
	 }
	 /**
	  * JSON 转 POJO
	  * @param map
	  * @param pojo
	  * @return
	  * @throws Exception
	  */
	 public  static Object   JsonToPojo(JSONObject json, Object pojo)   throws   Exception   {   
         
         
	        //   获得对象的类型   
	        Class   classType   =   pojo.getClass();   
	        //   获得对象的所有属性   
	        //Field   fields[]   =   classType.getDeclaredFields();   
	        //   Field   mapFields[]   =   null;   
	        //Iterator   keyValuePairs   =   map.entrySet().iterator();   
	        String[] key=JSONObject.getNames(json);
	        for   (int   i   =   0;   i    <   key.length;   i++)   {   
	        	//Field field=classType.getDeclaredField(key[i]);
	        	//Class carg=field.getClass();
	        	//value=new carg json.get(key[i]);
	            //Map.Entry   entry   =   (Map.Entry)   keyValuePairs.next();   
	            //String   key   =   (String)   entry.getKey();   
	            //String   value   =   (String)   entry.getValue();   
	        	try{
		            //String   firstKey   =   key[i].substring(0,1).toUpperCase();   
		            //   获得和属性对应的getXXX()方法的名字   
		            //String   getMethodName   =    "set"   +   firstKey   +   key[i].substring(1);   
		            //   获得和属性对应的getXXX()方法   
		            //Class[]   cargs   =   new   Class[1];    
		            
		            //String   realArgs   =   value;       
		            //Integer   in   =   new   Integer(2);   
		            //cargs[0]   =   realArgs.getClass();  
		        //classType.getm
		            //Method   getMethod   =   classType.getMethod(getMethodName);   
		            //   调用原对象的getXXX()方法   
		            //Object   test   =   getMethod.invoke(pojo,   json.get(key[i]));   
		            //System.out.println(test);   
	        		Field  field   =   classType.getDeclaredField(key[i]);
	        		field.setAccessible(true);
	        		field.set(pojo, json.get(key[i]));
	        	}
	        	catch(Throwable e)
	        	{
	        		
	        	}
	        }   
	        return   pojo;   
	    }  
	 
	 public String AddZero(int TicketNumber) throws Exception {
			int TicketNumberLength = 4;
			if((TicketNumber+"").length() < TicketNumberLength){
				String zero = "";
				int i = TicketNumberLength - (TicketNumber+"").length();
				for(int j=0;j<i;j++){
					zero += "0";
				}
				return zero + TicketNumber;
			}else{
				return TicketNumber + "";
			}
		}
}
